/**
 * 会员中心 公告
 */

$(document).ready(function(e) {	
	//$("DIV[name='memberMeetingroomlist']").hide();
	//$("DIV[name='viewInfo']").show();	
	//detail(34);
	getlist();
	initMemberList();//初始化参会人员
	
	$("#w1").html(getDay()+"<br>"+getWeek()).attr("data-day",getDays()).attr("data-week",getWeek());
	$("#selecttime").click(function(){
		laydate({elem:'#dayTime',istime: false,istoday: true, format: 'YYYY-MM-DD',min:laydate.now(),choose:beginDateCallBack});
	});
	$(".btn-yuding").click(function(){
		$data_time = $("#dayTime").val();
		if(!$data_time){
			alert("请选择预订时间！");return false;
		}
		$subject=$("#y_zhuti").val();
		if(!$subject){
			alert("请选输入会议主题！");return false;
		}
		$meetingroom_id = $("#w1").attr("data-id");
		$mem_info =getsm();
		
		if(!$mem_info){
			alert("请选择参会人员！");return false;
		}
		$mem_list='['+$mem_info+']';
		$range_ids =getsm(1);
		if(!$range_ids){
			alert("请选择预订时间！");return false;
		}
		
		$("#myModal").modal({
			toggle:"modal",
			target:"#myModal",
			keyboard: false,
			backdrop:"static"
		});
	})
	$("#btnsave").click(function(){
		var memberToken = localStorage.getItem('memberToken');
		$data_time = $("#dayTime").val();
		if(!$data_time){
			alert("请选择预订时间！");return false;
		}
		$subject=$("#y_zhuti").val();
		if(!$subject){
			alert("请选输入会议主题！");return false;
		}
		$meetingroom_id = $("#w1").attr("data-id");
		$mem_info =getsm();
	
		if(!$mem_info){
			alert("请选择参会人员！");return false;
		}
		$mem_list='['+$mem_info+']';
		$range_ids =getsm(1);
		if(!$range_ids){
			alert("请选择预订时间！");return false;
		}
		
		$range_id_list='['+$range_ids+']';
		$money=$("#y_price").attr("data-price");
		//date_time=2018-03-28&meetingroom_id=34&mem_list=%5B18%5D&money=30.0&range_id_list=%5B16%5D&subject=%E6%B5%8B%E8%AF%95
		requestJson={"date_time":$data_time,"meetingroom_id":$meetingroom_id,"mem_list":$mem_list,"money":$money,"range_id_list":$range_id_list,"subject":$subject};
		
		$.ajax({
	        url: '/euc/_meetingroom/meetingroomOrderSave',
	        data:requestJson,
	        beforeSend: function(request) {
	            request.setRequestHeader("token",memberToken );
	        },
	        dataType: 'JSON',
	        async: true,
	        contentType:'application/x-www-form-urlencoded',
	        type: 'POST',
	        success: function (result, textStatus, response) {
	        	if(result.status==0){
	        		alert("预订成功");
	        		window.location.reload();
	        	}else{
	        		alert(result.message);
	        	}

	        },
	        error: function () {
	        	console.log("error");
	        }  
	    });
		
	})

	
})
function beginDateCallBack(){
	$time = $("#dayTime").val();
	$id= $("#w1").attr("data-id");
	detail($id,$time);
}

function getlist(currentPage){
	var memberToken = localStorage.getItem('memberToken');
	var requestJson = getSearchParameter(currentPage);
	if(requestJson == false){
		return false;
	}
	$.ajax({
        url: '/euc/_meetingroom/meetingroomList',
        data:requestJson,
        beforeSend: function(request) {
            request.setRequestHeader("token",memberToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/x-www-form-urlencoded',
        type: 'POST',
        success: function (result, textStatus, response) {
        	if(result.status === -2){
        		gotoLogin();
        	}
        	//alert(JSON.stringify(result));
        	pageBean = result.data;
        	$("#userTable").empty();	    

        	$.each(result.data.list,function(i,data){
        		
        	if(data.meetingroomStatus ==="启用"){
        		html = '<li onclick="detail('+data.id+')"><div class="listleft"><img src="'+data.displayPicture+'" width="272" height="166"></div>'
    			+'<div class="listright"><h1>'+data.meetingroomName+'</h1><h2>￥'+data.meetingroomPrice+data.unit+'</h2>'
    			+'<p>'+data.seatCount+' 人 | '+data.meetingroomArea+' ㎡ </p><p>'+data.otherFacilities+'</p><p>'+data.space.address+'</p></div>';
        	$("#userTable").append(html);
        	}
        		
			});
        	$("#totalRow").html(pageBean.totalRow+'&nbsp;');
        	$("#currentPage").html(pageBean.currentPage+'&nbsp;');
        	$("#pageSize").html(pageBean.pageSize+'&nbsp;');        	
        	var pageLength = 15;
        	initailPageNumber(pageBean.totalPage,pageBean.currentPage,pageLength);        	
        	
        },
        error: function () {
        	console.log("error");
        }  
    });
}
function getSearchParameter(currentPage){
	var memberToken = localStorage.getItem('memberToken');
	var memberSpaceId = localStorage.getItem('memberSpaceId');
	try{

		if(!currentPage) currentPage=1;
		pn = currentPage;
		pn = pn==0 ? 1 : pn;
		ps =10;
		requestJson ={"pn":pn,"ps":ps,"space_id":memberSpaceId};
		return requestJson;
	}catch(e){
		console.log(e.messge);
	}
	return false;	
}

function detail(id,day){
	$("DIV[name='memberMeetingroomlist']").hide();
	$("DIV[name='viewInfo']").show();	
	
	var memberToken = localStorage.getItem('memberToken');
	var memberSpaceId = localStorage.getItem('memberSpaceId');
	if(!day){
		day = getDays();
		$("#dayTime").val(day);
	}else{
		$("#w1").html(getDay(day)+"<br>"+getWeek(day)).attr("data-day",day).attr("data-week",getWeek(day));;
	}

	
	requestJson = {"date_time":day,"meetingroom_id":id};
	$.ajax({
        url: '/euc/_meetingroom/meetingroomDetail',
        data:requestJson,
        beforeSend: function(request) {
            request.setRequestHeader("token",memberToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/x-www-form-urlencoded',
        type: 'POST',
        success: function (result, textStatus, response) {
        	    	
        	data=result.data;
        	$("#d_img").html('<img src="'+data.displayPicture+'" width="419" height="303" />');
        	$("#d_title").html(data.meetingroomName);
        	$("#d_price").html('￥ '+data.meetingroomPrice+data.priceUnit).attr('data-price',data.meetingroomPrice);
         	$("#d_p1").html(data.seatCount+' 人 | '+data.meetingroomArea+' ㎡');
        	$("#d_p2").html(data.otherFacilities);
        	$("#d_p3").html(data.space.address);
        	$("#w1").attr('data-id',data.id);
        	$("#d_time_d").html('');
        	
        	$time = getNow();//现在时间
        	$curday = getDays();
        	$_curday=false;
        	if($curday==day){
        		$_curday=true;
        	}
        	
        	$.each(data.rangeList,function(i,v){
        		
        		if(($_curday==true &&(checkTime($time,v.time) !== false)) || v.status==1 ){
        
        			var html = '<div class="col-sm-3 w_border2 nocr"';//去除
        		}else{
        			var html = '<div class="col-sm-3 w_border2" onclick="s('+v.id+','+data.meetingroomPrice+')"';
        		}

        			html +=' data-id="'+v.id+'" id="p'+v.id+'">'+v.time+'</div>';
        			
        		$("#d_time_d").append(html);
        		//if(v.time)
        		//<div class="col-sm-3 w_border2" id="w2">1月27日<br>周1</div>
        	});
        	$height =$("#timeleft").height() - 40;
   
        	$("#orderright").height($height);
        	
        },
        error: function () {
        	console.log("error");
        }  
    });
}
//选择 左侧时间块
function s(id,price){
	$name="#p"+id;
	var bid= eid=0;
	var cid= parseInt($($name).attr("data-id"));
	if($(".w_border2").hasClass("crb")){
		bid=parseInt($(".crb").attr("data-id"));
	}
	if($(".w_border2").hasClass("cre")){
		eid=parseInt($(".cre").attr("data-id"));
	}
	if(bid==0&&eid==0){
		bid=cid;
		$($name).addClass("crb");
	}else if(bid>0&&eid==0){

		if(bid<cid){
			$($name).addClass("cre");
			var eid=cid;
		}else{

			$(".crb").addClass("cre").removeClass("crb");
			$($name).addClass("crb");
			var eid=bid;
			var bid =cid;
		}
		var $status =0; //清除状态 初始
		for(var i=bid;i<eid;i++){
			name2="#p"+i;
			if($(name2).hasClass("nocr")){
				clearSelectTime();//清除选择状态
				$status =1;//清除状态 不结算
				break;
			}else{
				$(name2).addClass("cr");
			}
		}
		if($status==0){
			$jiange = parseFloat((eid - bid)).toFixed(1);
			$("#y_time").html($("#w1").attr("data-day")+"("+$("#w1").attr("data-week")+") "+$(".crb").text()+"~"+$(".cre").text()+"("+$jiange/2+"小时)");
			$("#y_price").html("￥ "+($jiange*price)).attr('data-price',$jiange*price);
		}else{
			$("#y_time").html("无法选择已预订时间");
			$("#y_price").html("").attr('data-price',price)
		}
		
	}else{
		clearSelectTime();//清除选择状态
		$($name).addClass("crb");
		var bid=cid;var eid=0;
	}
	

	
	
	//console.log($($name).text());
}
//清除选择状态
function clearSelectTime(){
	$(".w_border2").removeClass("crb").removeClass("cre").removeClass("cr");
}

//初始化参会人员
function initMemberList(){
	var memberToken = localStorage.getItem('memberToken');
	var memberId = localStorage.getItem('memberId');
	smadd(memberId,localStorage.getItem('memberName'));//添加 管理员自己
	requestJson = {"dept_id":""};
	$.ajax({
        url: '/euc/_user/member_list',
        data:requestJson,
        beforeSend: function(request) {
            request.setRequestHeader("token",memberToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/x-www-form-urlencoded',
        type: 'POST',
        success: function (result, textStatus, response) {
        	    	
        	data=result.data;
        	
        	$.each(data,function(i,v){
        			if(v.member_id==memberId){
        				var html = '<div class="col-sm-4 w_border3 mcr"';
        			}else{        				
        				var html = '<div class="col-sm-4 w_border3" onclick="sm('+v.member_id+',\''+v.member_name+'\')"';
        			}
        	
        			html +=' data-id="'+v.member_id+'" id="m'+v.member_id+'">';
        			if(!v.face_url){
        				html +='<img class="img-circle" src="./images/i07.png" alt="头像"/>';	
        			}else{
        				html +='<img class="img-circle" src="'+v.face_url+'" alt="头像"/>';	
        			}
        			html +=v.member_name+'<br>'+(!v.dept_name ? "" : v.dept_name)+'</div>';
        			
        		$("#y_memberList").append(html);

        	})
        	
        	
        },
        error: function () {
        	console.log("error");
        }  
    });
}

//选择参会人员
function sm(id,username){
	$name= "#m"+id;
	
	if($($name).hasClass("mcr")){//已选 去除
		$($name).removeClass("mcr");//删除用户
		smdel(id);
	}else{
		$($name).addClass("mcr");//增加
		smadd(id,username);
	}
}
//添加参会人员
function smadd(id,username){
	var memberId = localStorage.getItem('memberId');
	if(id==memberId){
		var html = '<div class="col-sm-3 w_border3 mlist mcr"';
	}else{        				
		var html = '<div class="col-sm-3 w_border3 mlist mcr" onclick="smdel('+id+')"';
	}

	html +=' data-id="'+id+'" id="ma'+id+'">'+username+'</div>';
	$("#y_member").append(html);
}
function getsm(type){
	if(type==1){
		data =$('#d_time_d .cr');
	}else{
		data =$('#y_member .mlist');
	}
	$list=new Array();
	$.each(data,function(i,attrib){
		$list.push($(this).attr("data-id"));
	});
	return $list.toString();
}
//删除参会者
function smdel(id){
	var memberId = localStorage.getItem('memberId');
	if(id!=memberId){
		$name="#ma"+id;
		$($name).remove();
	}
}


function getDay(day){
	if(!day){		
		var $time= new Date();
	}else{
		var fullDate = day.split("-");  
		var $time= new Date(fullDate[0], fullDate[1]-1, fullDate[2], 0, 0, 0);		
	}
	$month = parseInt($time.getMonth())+1;
	$day = parseInt($time.getDate());
	return $month +"月"+$day+"日";	
}
function getWeek(day){
	var weekday=new Array(7);
	weekday[0]="周日";
	weekday[1]="周一";
	weekday[2]="周二";
	weekday[3]="周三";
	weekday[4]="周四";
	weekday[5]="周五";
	weekday[6]="周六";
	
	if(!day){		
		var $time= new Date();
	}else{
		var fullDate = day.split("-");  
		var $time= new Date(fullDate[0], fullDate[1]-1, fullDate[2], 0, 0, 0);		
	}
	return weekday[parseInt($time.getDay())];	
}

//a为大时间
function checkTime(a,b){
	if(!a||!b) return false;
	
	var s="1970/1/1 ";
	var a1=Date.parse(s+a) + 1800000;
	var b1=Date.parse(s+b);

	if(a1 > b1){
		return true;
	} else{
		 return false;
	}
}
function getNow(){
	$time = new Date();
	return $time.getHours()+":"+$time.getMinutes();
}